package com.ahwei.user.util.easyexcel.controller;

import com.ahwei.common.rest.base.R;
import com.ahwei.common.rest.base.ResultCode;
import com.ahwei.common.rest.exception.ApplicationException;
import com.ahwei.user.util.easyexcel.entity.ExcelEntity;
import com.ahwei.user.util.easyexcel.listener.ExcelListener;
import com.ahwei.user.util.easyexcel.service.ExcelService;
import com.ahwei.user.util.easyexcel.util.ExcelUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.util.List;

/**
 * <p>
 * 这是一个Java文件！
 * </p>
 *
 * @author ahWei
 * @email：ahwei163@qq.com
 * @since 2022-06-15 19:15:50
 */
@Slf4j
@RestController
@RequestMapping("/excel")
public class ExcelController {
    @Autowired
    private ExcelService<ExcelEntity> excelService;



    /**
     * excel导出数据
     * @param response .
     */
    @GetMapping("/export")
    public void exportUser(HttpServletResponse response) {
        List<ExcelEntity> entityList = excelService.dataExport();
        Boolean result = ExcelUtils.writeExcel(response, ExcelEntity.class, entityList);
        if (!result) {
            throw new ApplicationException(ResultCode.UNKNOWN, "导出失败！");
        }
    }



    /**
     * excel批量导入用户数据
     * @param file .
     * @return .
     */
    @PostMapping("/import")
    public R<Object> addUserList(@RequestParam("file") MultipartFile file) {
        try {
            BufferedInputStream in = new BufferedInputStream(file.getInputStream());
            //调用写的一个工具类传入 文件流，所要转换存储的类，以及业务逻辑（我这边直接就是插入语句）
            ExcelUtils.readExcel(in, ExcelEntity.class, excelService);
            List<ExcelEntity> readData = (List<ExcelEntity>) ExcelListener.readData;

            if (readData.size() == 0) {
                throw new ApplicationException(ResultCode.UNKNOWN, "读取数据0条，导入失败！");
            }
            return R.ok(readData,"读取的数据");
        } catch (Exception e) {
            throw new ApplicationException(ResultCode.UNKNOWN, "导入失败！");
        }
    }




    /**
     * 批量导入需要先下载模板
     * @param response .
     */
    @GetMapping("/excelTemplate")
    public void downloadExcel(HttpServletResponse response) {
        String templateFilePath = this.getClass().getResource("/").getPath() + "/用户数据导入模板.xlsx";
        log.debug("\n==> 正在下载excel模板{}", templateFilePath);
        try (FileInputStream in = new FileInputStream(templateFilePath)) {
            String fileName = "用户数据导入模板";
            //通知浏览器以附件的形式下载处理，设置返回头要注意文件名有中文
            response.setHeader("Content-disposition", "attachment;filename=" + new String(fileName.getBytes("gb2312"), "ISO8859-1") + ".xlsx");
            response.setContentType("multipart/form-data");
            response.setCharacterEncoding("utf-8");
            OutputStream os = response.getOutputStream();
            byte[] b = new byte[1024];
            int len;
            while ((len = in.read(b)) > 0) {
                os.write(b, 0, len);
            }
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
